package com.ldk.framework.service.impl;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ldk.base.framework.common.CustomException;
import com.ldk.base.framework.dao.IBaseDAO;
import com.ldk.base.framework.service.impl.BaseService;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.Driver;
import com.ldk.framework.service.ICommentService;
import com.ldk.framework.service.IDriverService;
import com.ldk.framework.service.IExpressOrderImagesService;
import com.ldk.framework.service.IExpressOrderService;
import com.ldk.framework.dao.IExpressOrderDAO;
import com.ldk.framework.entity.Comment;
import com.ldk.framework.entity.ExpressOrder;
import com.ldk.framework.entity.ExpressOrderImages;
import com.ldk.framework.enums.ExpressOrderStatus;

/**
* ExpressOrderService接口实现类
* @author xiangwl
*/
@Service
public class ExpressOrderService extends BaseService<ExpressOrder> implements IExpressOrderService {

	@Autowired
	private IExpressOrderDAO expressOrderDAO;
	@Autowired
	private IExpressOrderImagesService expressOrderImagesService;
	@Autowired
	private ICommentService commentService;
	@Autowired
	private IDriverService driverService;

	@Override
	protected IBaseDAO<ExpressOrder> getBaseDao() {
     	return this.expressOrderDAO;
	}
	
	@Override
	@Transactional(rollbackFor={Exception.class, CustomException.class, NullPointerException.class, SQLException.class, IOException.class})
	public Boolean publish(String dbKey, ExpressOrder model, List<ExpressOrderImages> images) throws Exception {
		if(model == null || images == null || images.isEmpty())
			return false;
		try{
			int row = insert(dbKey, model);
			if(row < 1)
				throw new CustomException("发布快递订单失败");
			for (ExpressOrderImages item : images) {
				row = expressOrderImagesService.insert("", item);
				if(row < 1){
					throw new CustomException("发布快递订单货物图片保存失败");
				}
			}
			return row > 0;
		}
		catch(Exception e){
			logger.error(e.getMessage());
			throw new CustomException(e.getMessage());
		}
	}

	@Override
	@Transactional(rollbackFor={Exception.class, CustomException.class, NullPointerException.class, SQLException.class, IOException.class})
	public Boolean complete(String dbKey, String orderNo, Boolean hasComment, Integer star , String content)
			throws Exception {
		if(StringUtils.isBlank(orderNo)) return false;
		ExpressOrder query = new ExpressOrder();
		query.setOrderNo(orderNo);
		
		ExpressOrder order =  selectOne(dbKey, query);
		if(order == null){
			throw new CustomException("订单不存在");
		}
		//只有接单状态的才可以完成
		if(order.getStatus() != ExpressOrderStatus.Receive.getValue()){
			throw new CustomException("订单状态错误");
		}
		try{
			ExpressOrder entity = new ExpressOrder();
			entity.setOrderNo(orderNo);
			entity.setStatus(ExpressOrderStatus.Complete.getValue());
			entity.setCompleteTime(SystemUtil.getAllSeconds());
			entity.setHasComment(hasComment);
			
			int row = updateByKey(dbKey, entity);
			if(row < 1){
				throw new CustomException("修改订单状态失败");
			}
			if(hasComment){
				Comment commentQuery = new Comment();
				commentQuery.setToOrderNo(orderNo);
				Comment comment = commentService.selectOne(dbKey, commentQuery);
				if(comment == null){
					comment = new Comment();
					comment.setCommentNo(SystemUtil.generateSn(""));
					comment.setFromOpenId(order.getPublisher());
					comment.setToOrderNo(orderNo);
					comment.setToOpenId(order.getDeliveryPerson());
					star = Math.min(star, 5);
					star = Math.max(star, 0);
					comment.setStar(star);
					comment.setContent(content);
					comment.setTime(SystemUtil.getAllSeconds());
					comment.setEnabled(true);
					
					row = commentService.insert(dbKey, comment);
					//修改司机的星级
					String driverOpenId = comment.getToOpenId();
					double driverStar = commentService.calculateStar(dbKey, driverOpenId);
					Driver driverQuery = new Driver();
					driverQuery.setOpenId(driverOpenId);
					
					Driver driver = driverService.selectOne(dbKey, driverQuery);
					if(driver != null){
						Driver driverEntity = new Driver();
						driverEntity.setDriverId(driver.getDriverId());
						driver.setStar(driverStar);
						driverService.updateByKey(dbKey, driver);
					}
				}
				
			}
			return row > 0;
		}
		catch(Exception e){
			logger.error(e.getMessage());
			throw new CustomException(e.getMessage());
		}
	}
}
